package com.web.dao.impl;

import com.web.dao.UserDao;
import com.web.domain.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Created by 陈国钰 on 2016/9/5.
 */
@Repository
public class UserDaoImpl implements UserDao {
    @Resource
    SessionFactory factory;
    private JdbcTemplate jdbcTemplate;

    public void update(User user) {
        factory.getCurrentSession().merge(user);
    }

    public void save(User user) {
        factory.getCurrentSession().persist(user);
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public User find(String UserName) {
        StringBuffer hql = new StringBuffer();
        hql.append(" from User as User");
        hql.append(" where UserName = '");
        hql.append(UserName);
        hql.append("'");
        return (User) factory.getCurrentSession().createQuery(hql.toString()).list().get(0);
    }


    public User get(int UserId) {
        return (User) factory.getCurrentSession().load(User.class, UserId);
    }


    public boolean saveOrUpdateUser(User User) {
        // TODO Auto-generated method stub
        Session session = null;
        try {
            session = this.factory.getCurrentSession();
            session.saveOrUpdate(User);
            return true;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

}
